import {defineStore} from 'pinia'

import {useUserStore} from '@/store/modules/useUserStore'

import {ref, computed} from 'vue'

import {get, post} from '@/utils/request'

export const useDeviceStore = defineStore('device', () => {

    const curDevUserId = ref();

    const getDevUserId = computed(() => {
        return curDevUserId.value;
    })
    
    const setDevUserId = (userId) => {
        curDevUserId.value = userId;
    }

    // 设备列表
    const deviceList = ref([
        {
            id: 1,
            sn: 'WATCH2024001',
            mac: '00:1A:2B:3C:4D:5E',
            deviceType: 'wearable',
            status: 'active',
            metaData: {
                name: '爷爷的智能手表',
                note: '日常使用'
            },
            lastSyncTime: '2024-03-20T10:30:00Z'
        },
        {
            id: 2,
            sn: 'BAND2024002',
            mac: '00:2B:3C:4D:5E:6F',
            deviceType: 'wearable',
            status: 'inactive',
            metaData: {
                name: '奶奶的智能手环',
                note: '日常使用'
            },
            lastSyncTime: '2024-03-19T15:45:00Z'
        }
    ])

    // 当前选中的设备
    const selectedDevice = ref(null)

    // Getters
    const getDeviceList = computed(() => deviceList.value)
    const getSelectedDevice = computed(() => selectedDevice.value)
    // 根据 SN 获取设备
    const getDeviceBySN = computed(() => (deviceSN) => {
        return deviceList.value.find(d => d.sn === deviceSN);
    });

    // 设置选中的设备
    function setSelectedDevice(device) {
        selectedDevice.value = device
    }

    // 获取设备列表
    const fetchDeviceList = async (userId) => {

        if(!userId){
            userId = curDevUserId.value 
        }

        try {
            const res = await get(`/devices/${userId}`, 'api/v1')
            if (res && res?.code === 200) {
                deviceList.value = res.data
            } else if (res) {
                console.log(res?.msg)
                // 不抛出错误，允许使用默认数据
                // throw new Error(res?.msg || '获取设备列表失败');
            }
            // 无论成功失败都返回当前 store 中的 deviceList
            return deviceList.value
        } catch (error) {
            console.log("fetchDeviceList error:", error)
            // 不抛出错误，允许使用默认数据
            // throw error
            // 无论成功失败都返回当前 store 中的 deviceList
            return deviceList.value
        }
    }

    // 同步设备状态和信息
    const syncDeviceStatusAndInfo = async (deviceSN) => {
        try {
            console.log("Syncing device status and info for SN:", deviceSN);
            // 使用获取设备状态的接口来同步最新信息
            const res = await get(`/devices/${deviceSN}/status`, 'api/v1');
            console.log("syncDeviceStatusAndInfo response:", res);

            if (!res) {
                 throw new Error('同步设备状态失败：无响应');
            }

            if (res?.code === 200 && res?.data) {
                // 更新 store 中对应设备的 status, lastSyncTime 和 metaData
                const deviceIndex = deviceList.value.findIndex(d => d.sn === deviceSN);
                if (deviceIndex !== -1) {
                    deviceList.value[deviceIndex].status = res.data.status;
                    deviceList.value[deviceIndex].lastSyncTime = res.data.lastSyncTime;
                    // 注意：status接口返回的metaData可能不全，只更新部分字段
                     if (res.data.metaData) {
                         deviceList.value[deviceIndex].metaData = { ...deviceList.value[deviceIndex].metaData, ...res.data.metaData };
                     }
                }
                console.log("Device info synced for SN:", deviceSN);
                return res.data; // 返回同步到的最新状态和元数据
            } else {
                throw new Error(res.msg || '同步设备状态失败');
            }
        } catch (error) {
             console.log("syncDeviceStatusAndInfo error:", error);
             if (error.errMsg === 'request:fail') {
                 throw new Error('同步设备状态失败：网络请求失败，请检查网络连接');
             }
             throw error;
        }
    }

    // 添加设备（自动生成并绑定）
    const addDevice = async (type, meta) => {
        try {
            console.log("addDEV", type, meta);

            const requestData = {
                userId: curDevUserId.value,
                type: type,
                metaData: meta
            };
            console.log("请求数据:", requestData);

            const res = await post('/devices/makeAndBindDev', requestData, 'api/v1');
            console.log("addDevice response:", res);

            if (!res) {
                throw new Error('请求失败，请检查网络连接');
            }

            if (res.code === 200) {
                // makeAndBindDev 返回的是 Result.success 格式，data 字段包含新设备对象
                if (res.data) {
                    deviceList.value.push(res.data);
                     // 同步新设备的状态和信息
                    await syncDeviceStatusAndInfo(res.data.sn);
                    return res.data;
                }
                // 如果没有 data 字段，也返回成功响应
                return res;
            } else {
                throw new Error(res.msg || '添加设备失败');
            }
        } catch (error) {
            console.log("addDevice error:", error);
            if (error.errMsg === 'request:fail') {
                throw new Error('网络请求失败，请检查网络连接');
            }
            throw error;
        }
    }

    // 解绑设备
    const unbindDevice = async (deviceSN) => {
        try {
            const res = await post('/devices/unbind', {
                userId: curDevUserId.value,
                deviceSN: deviceSN
            }, 'api/v1')

            if (res?.code === 200) {
                deviceList.value = deviceList.value.filter(d => d.sn !== deviceSN)
                return res.data
            } else if (res) {
                console.log(res?.msg)
                throw new Error(res?.msg || '解绑设备失败')
            }
        } catch (error) {
            console.log(error)
            throw error
        }
    }

    // 测试API
    const testApi = async () => {
        try {
            // 测试添加设备
            const device1 = await addDevice('wearable')
            // 测试获取设备列表
            await fetchDeviceList(curDevUserId.value)
            // 测试同步设备数据
            await syncDeviceStatusAndInfo(device1.sn)
            // 测试解绑设备
            await unbindDevice(device1.sn)

            console.log('test api success')
        } catch (error) {
            console.log(error)
            return error
        }
    }

    return {
        deviceList,
        selectedDevice: computed(() => selectedDevice.value),
        getDeviceList,
        getSelectedDevice: computed(() => selectedDevice.value),
        setSelectedDevice,
        fetchDeviceList,
        syncDeviceStatusAndInfo,
        addDevice,
        unbindDevice,
        testApi,
        getDeviceBySN,
        getDevUserId,
        setDevUserId,

    }
})


